package com.atguigu.day01;

import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Example3 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<String> stringDataStreamSource = env.fromElements("hello world", "hello flink");
        stringDataStreamSource.flatMap((String line, Collector<WordWithCount> out) -> {
            String[] words = line.split(" ");
            for (String word : words) {
                out.collect(new WordWithCount(word, 1L));
            }
        }).returns(WordWithCount.class)
                .keyBy(wordWithCount -> wordWithCount.word)
                .reduce((WordWithCount value1, WordWithCount value2) -> new WordWithCount(value1.word, value1.value + value2.value))
                .print();
        env.execute();
    }

    public static class WordWithCount {
        public String word;
        public Long value;

        public WordWithCount(String word, Long value) {
            this.word = word;
            this.value = value;
        }

        @Override
        public String toString() {
            return "WordWithCount{" +
                    "word='" + word + '\'' +
                    ", value=" + value +
                    '}';
        }

    }
}
